package net

import (
	"bytes"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"tcp-proxy/src/config"
	"tcp-proxy/src/util"
	time2 "time"
)

type Device struct {
	Number                string `json:"number"`
	Time                  int64  `json:"time"`
	Rev                   string `json:"rev"`
	FuelConsumption       string `json:"fuel_consumption"`
	ManHour               string `json:"man_hour"`
	IdlingFuelConsumption string `json:"idling_fuel_consumption"`
	IdlingManHour         string `json:"idling_man_hour"`
	Lng                   string `json:"lng"`
	Lat                   string `json:"lat"`
	Date                  string `json:"date"`
	DateTime              string `json:"date_time"`
	UserId                string `json:"user_id"`
	ErrorCount            string `json:"error_count"`
	Average               string `json:"average"`
	Mileage               string `json:"mileage"`
	OilIn                 string `json:"oil_in"`
	OilOf                 string `json:"oil_of"`
	Error                 string `json:"error"`
	Command               string `json:"command"`
	AddTime               string `json:"add_time"`
}

func NewDevice() *Device {
	return &Device{
		Command: "EQUIPMENT-PUSH",
	}
}

func NewShortDevice(number, fuelConsumption, manHour, idlingFuelConsumption, idlingManHour, date string) *Device {
	return &Device{
		Command:               "EQUIPMENT-STATEMENT",
		Number:                number,
		FuelConsumption:       fuelConsumption,
		ManHour:               manHour,
		IdlingFuelConsumption: idlingFuelConsumption,
		IdlingManHour:         idlingManHour,
		Date:                  date,
	}
}

func (d *Device) Send() {
	var url = config.GlobalConfig.Request.Url
	time := time2.Now().Format("2006-01-02 15:04:05")
	operatorId := "5D11E0F2EAD790BB"
	sign := util.MD5(util.SHA1(operatorId + time))
	JsonStr, _ := json.Marshal(d)
	if config.GlobalConfig.Server.Log {
		log.Println("发送数据，等待响应：", string(JsonStr))
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(JsonStr))
	req.Header.Set("Content-Type", "application/Json")
	req.Header.Add("datetime", time)
	req.Header.Add("sign", sign)
	req.Header.Add("command", "2")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	if config.GlobalConfig.Server.Log {
		log.Println("返回响应结果：", string(body))
	}
}
